package com.geekhalo.admin.domain.menu;

import com.geekhalo.admin.domain.menu.create.CreateMenuCommand;
import com.geekhalo.admin.domain.menu.create.CreateMenuContext;
import com.geekhalo.admin.domain.menu.create.CreateMenuContext;
import com.geekhalo.admin.domain.menu.create.MenuCreatedEvent;
import com.geekhalo.admin.domain.menu.update.MenuUpdatedEvent;
import com.geekhalo.admin.domain.menu.update.UpdateMenuCommand;
import com.geekhalo.admin.domain.menu.update.UpdateMenuContext;
import com.geekhalo.admin.domain.menu.update.UpdateMenuContext;
import com.geekhalo.lego.core.command.support.AbstractAggRoot;
import lombok.AccessLevel;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.persistence.*;

@Entity
@Table(name = "menu")
@Data
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Setter(AccessLevel.PRIVATE)
public class Menu extends AbstractAggRoot { 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private Long appId;

    private Long parentMenuId;

	private String path;

    private String icon;

    private String name;

    private String descr;

	private String component;


    public static Menu create(CreateMenuContext context) {
        Menu agg = new Menu();
        agg.readFrom(context.getCommand());
        agg.init();
        return agg;
    }


	// 自动生成代码，勿动
	private void readFrom(CreateMenuCommand source){
		if(source.getAppId() != null){
			this.setAppId(source.getAppId());
		}
		if(source.getParentMenuId() != null){
			this.setParentMenuId(source.getParentMenuId());
		}
		if(source.getIcon() != null){
			this.setIcon(source.getIcon());
		}
		if(source.getName() != null){
			this.setName(source.getName());
		}
		if(source.getDescr() != null){
			this.setDescr(source.getDescr());
		}
	}

    private void init() {
        //添加代码
        addEvent(new MenuCreatedEvent(this));
    }


    public void update(UpdateMenuContext context) {
        readFrom(context.getCommand());
        addEvent(new MenuUpdatedEvent(this));
    }


	// 自动生成代码，勿动
	private void readFrom(UpdateMenuCommand source){
		if(source.getIcon() != null){
			this.setIcon(source.getIcon());
		}
		if(source.getName() != null){
			this.setName(source.getName());
		}
		if(source.getDescr() != null){
			this.setDescr(source.getDescr());
		}
	}
}